﻿using System;
using System.Xml;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TrinityAPI.Formatter
{
    public class XmlMediaTypeFormatter : MediaTypeFormatter
    {
        public XmlMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(string) || type == typeof(JToken) || type.IsSubclassOf(typeof(JToken));
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(string) || type == typeof(JToken) || type.IsSubclassOf(typeof(JToken));
        }

        public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream,
            HttpContent content, IFormatterLogger formatterLogger)
        {
            using (var sr = new StreamReader(readStream))
            {
                var request = await sr.ReadToEndAsync();
                try
                {
                    XmlDocument doc = new XmlDocument();
                    //2.加载 xml 文档
                    doc.LoadXml(request);
                    //3.xml文档转换为 Json 格式
                    string json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None);

                    return JToken.Parse(json);
                }
                catch (Exception ex)
                {
                    throw new Exception("There is an error in the xml syntax: " + ex.Message);
                }
            }
        }
    }
}